import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/bottom_sheet.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:universal_html/html.dart' as html;

import '../../widget/photo_view.dart';

class CyclePublishUi extends StatelessWidget {
  const CyclePublishUi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _MomentPublishWidget();
  }
}

class _MomentPublishWidget extends StatefulWidget {
  const _MomentPublishWidget({Key? key}) : super(key: key);

  @override
  State<_MomentPublishWidget> createState() => _MomentPublishWidgetState();
}

class _MomentPublishWidgetState extends State<_MomentPublishWidget> {

  var _visitPermission = 0;
  final _contentController = TextEditingController();

  @override
  Widget build(BuildContext context) {


    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          "新动态",
          style: TextStyle(color: ThemeColor.textColor, fontSize: 16,),
        ),
        elevation: 0,
        centerTitle: true,
        leading: const BackButton(color: Colors.black),
      ),
      body: Column(
        children: [
          Expanded(child: SingleChildScrollView(
            child: Column(
              children: [

                _buildEdit(),
                _buildPicture(),
                _SelectStatus(),

              ],
            ),
          )
          ),
          Container(
            color: Colors.white,
            height: 100,
            child: Align(

              alignment: Alignment.bottomCenter,
              child: GestureDetector(
                onTap: (){
                  _publish();

                },
                child: Container(
                  margin: const EdgeInsets.only(bottom: 30,top: 0,left: 50,right: 50),
                  height: 40,
                  // width: 200,
                  alignment: Alignment.center,
                  decoration: ShapeDecoration(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20)
                    ),
                    color: ThemeColor.appColor,
                  ),
                  // child: const Text("私聊", style: TextStyle(color: Colors.white),),
                  child: const Center(
                    child: Text(
                      "马上发布",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.normal),
                    )
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }



  Widget _buildEdit() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 0),
      height: 120,
      child: TextFormField(
        controller: _contentController,
        maxLines: 10,
        decoration: InputDecoration(
          hintText: "说点什么，让大家看到不一样的你～",
          hintStyle: TextStyle(
              color: ThemeColor.textColorSecond, fontSize: 14),
          enabledBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent)),
          focusedBorder: const UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent)),
        ),
        onSaved: (value) {
          if (value != null && value.isNotEmpty) {}
        },
      ),
    );
  }

  Widget _SelectStatus(){
    return GestureDetector(
      onTap: () async {
        final res = await BottomSheetDialog.showMenuByNames(context, ["公开", "仅好友可见"]);
        if (res == 1) {
          setState(() {
            _visitPermission = 10;
          });
        } else if (res == 0) {
          setState(() {
            _visitPermission = 0;
          });
        }
      },
      child: Container(
        margin: const EdgeInsets.only(top: 0, left: 20),
        padding: const EdgeInsets.only(right: 20),
        height: 50,
        decoration: const BoxDecoration(
            border: Border(
                bottom: BorderSide(
                    width: 1,
                    color: Color(0xFFEDEAEF)
                )
            )
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Expanded(child: Text("谁可以看", style: TextStyle(fontSize: 15, color: Color(0xFF222222)),)),
            Text(_visitPermission == 10 ? "好友可见" : "公开", style: TextStyle(color: ThemeColor.textColorSecond),),
            const SizedBox(width: 12,),
            const Icon(Icons.arrow_forward_ios, size: 15, color: Color(0xFFB4B1B6),)
          ],
        ),
      ),
    );
  }

  final List<String> _localFiles = [];
  Widget _buildPicture() {
    return SizedBox(
      height: 130,
      child:GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          childAspectRatio: 1,
        ),
        itemBuilder: (ctx, index) {
          if (_localFiles.length < 9 && index == _localFiles.length) {
            return GestureDetector(
              onTap: () { _onItemClick(index); },
              child: Container(
                margin: EdgeInsets.only(left: 10,bottom: 10,right: 10),
                // width: 100,
                // height: 100,
                // color: const Color(0xFFFBF8F9),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: const Color(0xFFFBF8F9),
                ),
                child: const Center(
                  child: Icon(
                    Icons.add,
                    color: Color(0xFFBBB8B9),
                    size: 32,
                  ),
                ),
              ),
            );
          }
          return GestureDetector(
            onTap: () { _onItemClick(index); },
            child: Container(

              margin: EdgeInsets.only(left: 10,bottom: 10,right: 10),

              child: ClipRRect(
                borderRadius: BorderRadius.circular(5),
                child: Image.network(
                  _localFiles[index],
                  // width: 100,
                  // height: 100,
                  fit: BoxFit.cover,
                ),
              ),

            ),
          );
        },
        itemCount: _localFiles.length < 9 ? _localFiles.length + 1 : _localFiles.length,
      ),
    );
  }

  // Widget _buildPicture() {
  //   return SizedBox(
  //     height: 100,
  //     child: ListView.builder(
  //       scrollDirection: Axis.horizontal,
  //       itemBuilder: (ctx, index) {
  //         if (_localFiles.length < 9 && index == _localFiles.length) {
  //           return GestureDetector(
  //             onTap: () { _onItemClick(index); },
  //             child: Container(
  //               margin: EdgeInsets.only(left: index == 0 ? 12 : 10),
  //               width: 100,
  //               height: 100,
  //               // color: const Color(0xFFFBF8F9),
  //               decoration: BoxDecoration(
  //                 borderRadius: BorderRadius.circular(5),
  //                 color: const Color(0xFFFBF8F9),
  //               ),
  //               child: const Center(
  //                 child: Icon(
  //                   Icons.add,
  //                   color: Color(0xFFBBB8B9),
  //                   size: 32,
  //                 ),
  //               ),
  //             ),
  //           );
  //         }
  //         return GestureDetector(
  //           onTap: () { _onItemClick(index); },
  //           child: Container(
  //
  //             margin: EdgeInsets.only(left: index == 0 ? 12 : 10),
  //             child: ClipRRect(
  //                 borderRadius: BorderRadius.circular(4),
  //               child: Image.network(
  //                 _localFiles[index],
  //                 width: 100,
  //                 height: 100,
  //                 fit: BoxFit.cover,
  //               ),
  //             ),
  //
  //           ),
  //         );
  //       },
  //       itemCount: _localFiles.length < 9 ? _localFiles.length + 1 : _localFiles.length,
  //     ),
  //   );
  // }

  _onItemClick(int index) {
    if (_localFiles.length < 9 && index == _localFiles.length) {
      getAlbumImg();
    } else {
      Navigator.push(
          context,
          MaterialPageRoute(
              builder: (_) => PhotoPreview(
                galleryItems: _localFiles,
                defaultImage: index,
              )
          )
      );
    }
  }

  /// 打开相册
  void getAlbumImg() {
    if (kIsWeb) {
      loading(() async {
        final uploadInputElement = html.FileUploadInputElement();
        uploadInputElement.multiple = false;
        uploadInputElement.draggable = true;
        uploadInputElement.click();
        uploadInputElement.onChange.listen((event) {
          final file = uploadInputElement.files?.first;
          if (file != null) {
            final formData = html.FormData();
            formData.appendBlob("photos", file.slice(), file.name);
            Api.getInstance().uploadMomentFromHtml(formData, (e) {
              if (e['code'] == 0) {
                final list = e['data'];
                if (list != null && list is List && list.isNotEmpty) {
                  for (var element in list) {
                    _localFiles.add(element);
                  }
                  setState(() { });
                } else {
                  toast("上传失败");
                }
              } else {
                ThemeSnackBar.show(context, e['msg']);
              }
            });
          }
        });
      });
    } else {
      loading(() async {
        final picker = ImagePicker();
        final pickerFile = await picker.pickImage(source: ImageSource.gallery);
        if (pickerFile != null) {
          CroppedFile? croppedImage = await ImageCropper().cropImage(
              sourcePath: pickerFile.path, //图片资源
              maxHeight: 500,
              maxWidth: 500,
              aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1), //裁剪框比例
              uiSettings: [
                AndroidUiSettings(
                    toolbarTitle: '裁剪',
                    lockAspectRatio: true //锁定图片纵横比
                ),
                IOSUiSettings(
                    title: '裁剪',
                    resetButtonHidden: true, //不显示重置按钮
                    aspectRatioLockEnabled: true, //锁定图片纵横比
                    aspectRatioPickerButtonHidden: true, //隐藏切换纵横比按钮
                    doneButtonTitle: "完成", //confirm按钮文字
                    cancelButtonTitle: "取消" //cancel按钮文字
                )
              ]
          );//根据XFile对象的路径获得图片进行裁剪
          //裁剪完成

          if(croppedImage != null) {

            //裁剪后图片的路径
            String filepath = croppedImage.path;
            final res = await Api.getInstance().uploadMomentPic(filepath);
            if (res?['code'] == 0) {
              final list = res['data'];
              if (list != null && list is List && list.isNotEmpty) {
                for (var element in list) {
                  _localFiles.add(element);
                }
                setState(() { });
              } else {
                toast("发生了一个未知错误...");
              }
            } else {
              toast(res?['msg']??"上传失败...");
            }
          }
        }
        // if (pickerFile != null) {
        //   final res = await Api.getInstance().uploadMomentPic(pickerFile.path);
        //   print('lllll $res');
        //   if (res?['code'] == 0) {
        //     final list = res['data'];
        //     if (list != null && list is List && list.isNotEmpty) {
        //       for (var element in list) {
        //         _localFiles.add(element);
        //       }
        //       setState(() { });
        //     } else {
        //       toast("发生了一个未知错误...");
        //     }
        //   } else {
        //     toast(res?['msg']??"上传失败...");
        //   }
        // }
      });
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _contentController.dispose();
  }

  _publish() async{
    if (_contentController.text.isEmpty) {
      return;
    }
    EasyLoading.show();
    String urls = "";
    if (_localFiles.isNotEmpty) {
      for (var element in _localFiles) {
        urls += "$element,";
      }
    }
    final res = await Api.getInstance().publishMood(
      Provider.memberId,
      _contentController.text,
      urls,
      _visitPermission,
      []
    );
    if (res['code'] == 0) {
      Navigator.pop(context, 0);
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
    EasyLoading.dismiss();
  }


  Widget _buildTitleBar() {
    return Container(
      height: 56,
      padding: const EdgeInsets.symmetric(horizontal: 12),
      color: Colors.white,
      child:  Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            height: 56,
            alignment: Alignment.center,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: Text("取消", style: TextStyle(color: ThemeColor.textColor),),
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12),
            height: 32,
            decoration: ShapeDecoration(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(4)
                ),
                color: ThemeColor.mainColor
            ),
            alignment: Alignment.center,
            child: GestureDetector(
              onTap: () {
                _publish();
              },
              child: const Text("发表", style: TextStyle(color: Colors.white),),
            ),
          )
        ],
      ),
    );
  }
}

